<?php
//
namespace app\home\controller;

use app\common\model\ShopGoodsGevalModel;
use app\common\model\ShopGoodsModel;
use app\common\model\ShopGoodsSkuModel;
use app\common\model\ShopOrderGoodsModel;
use app\common\model\ShopOrderLogModel;
use app\common\model\ShopOrderModel;
use app\common\model\ShopOrderRefundModel;
use app\common\model\ShopPromotionCardItemModel;
use app\common\model\ShopPromotionCardModel;
use app\common\model\ShopPromotionCardOrderModel;
use app\common\model\ShopPromotionGroupbuyCartModel;
use app\common\model\UserMemberAccountModel;
use app\common\model\UserMemberModel;
use app\common\model\UserModel;
use think\Request;

class OrderController extends BaseController
{

    private $orderModel;
    private $orderGoodsModel;
    private $orderLogModel;
    private $orderGevalModel;
    private $orderRefundModel;
    private $promotionGroupbuyCartModel;
    private $goodsModel;
    private $goodsSkuModel;
    private $promotionCardModel;
    private $promotionCardItemModel;
    private $promotionCardOrderModel;

    public function __construct(Request $request)
    {
        parent::__construct($request);
        if ($this->getMemberUid() <= 0) {
            $url = url('home/Public/userLogin', ['url' => urlencode($_SERVER['HTTP_REFERER'])]);
            $this->error('请先登录！', $url);
        }
        $this->orderModel      = new ShopOrderModel();
        $this->orderGoodsModel = new ShopOrderGoodsModel();
        $this->orderLogModel = new ShopOrderLogModel();
        $this->orderGevalModel = new ShopGoodsGevalModel();
        $this->orderRefundModel = new ShopOrderRefundModel();
        $this->promotionGroupbuyCartModel = new ShopPromotionGroupbuyCartModel();
        $this->promotionCardOrderModel = new ShopPromotionCardOrderModel();
        $this->promotionCardItemModel = new ShopPromotionCardItemModel();
        $this->promotionCardModel = new ShopPromotionCardModel();
        $this->goodsModel=new ShopGoodsModel();
        $this->goodsSkuModel = new ShopGoodsSkuModel();
    }

    /*
     * 订单列表
     */
    public function index()
    {
        $orderGenre = $this->request->param('order_genre', 0);
        $buyerUid   = $this->request->param('uid', $this->getMemberUid());
        if ($buyerUid <= 0) {
            $this->error('buyerUid error!');
        }
        $begin_time = $this->request->param('begin_time');
        if(empty($begin_time)){
            $begin_time='0';
        }else{
            $begin_time=$begin_time.' 00:00:00';
            $query['begin_time'] = $begin_time;
        }
        $end_time = $this->request->param('end_time');
        if(empty($end_time)){
            $end_time=date('Y-m-d').' 23:59:59';
        }else{
            $end_time=$end_time.' 23:59:59';
            $query['end_time'] = $end_time;
        }
        $map['buyer_uid']   = $buyerUid;
        $query['buyer_uid'] = $buyerUid;
        switch ($orderGenre) {
            case 0: //全部订单
                $map['order_status'] = ['egt',0];
                break;
            case 1: //待付款
                $map['order_status'] = ['egt',0];
                $map['pay_status'] = 0;
                break;
            case 2: //待发货
                $map['pay_status'] = 1;
                $map['order_status'] = ['egt',0];
                $map['shipping_status'] = 0;
                break;
            case 3: //待收货
                $map['order_status'] = ['egt',0];
                $map['shipping_status'] = 1;
                $map['order_status']    = 1;
                break;
            case 4: //待评价
                $map['order_status'] = 2;
                $map['geval_status'] = 0;
                break;
            default:
                $map['order_status'] = ['egt',0];
                break;
        }
        $list = $this->orderModel->where($map)->where('create_time','BETWEEN',array(strtotime($begin_time),strtotime($end_time)))->order('create_time desc')->paginate(12, false, [
            'query' => $query,
        ]);
        //echo $this->orderModel->getLastSql();
        foreach ($list as $k => $v) {
            $list[$k]['item_list'] = $this->orderGoodsModel->where('order_id', $v['order_id'])->select();
        }
        if ($this->request->isAjax()) {
            return $list;
        }
        $this->assign('list', $list);
        $this->assign('query', $query);
        $this->assign('orderGenre', $orderGenre);
        //dump($list->toArray());
        return $this->fetch();
    }
    /*
     * 优惠活动订单
     */
    public function promotionOrder(){
        $promotionTpl = [1=>'presell',2=>'seckill',3=>'point',4=>'groupbuy',5=>'auction'];
        $orderGenre = $this->request->param('order_genre', 0);
        $promotiontType=$this->request->param('promotion_type');
        if($promotiontType==4){
            $model=$this->promotionGroupbuyCartModel;
        }
        $member_uid   = $this->request->param('member_uid', $this->getMemberUid());
        if ($member_uid <= 0) {
            $this->error('用户信息错误，请重新登录!');
        }
        $begin_time = $this->request->param('begin_time');
        if(empty($begin_time)){
            $begin_time='0';
        }else{
            $begin_time=$begin_time.' 00:00:00';
            $query['begin_time'] = $begin_time;
        }
        $end_time = $this->request->param('end_time');
        if(empty($end_time)){
            $end_time=date('Y-m-d').' 23:59:59';
        }else{
            $end_time=$end_time.' 23:59:59';
            $query['end_time'] = $end_time;
        }
        $map['member_uid']   = $member_uid;
        $query['member_uid'] = $member_uid;
        switch ($orderGenre) {
            case 0: //全部订单
                break;
            case 1: //未付保障金
                $map['margin_status'] = 0;
                break;
            case 2: //已支付保障金
                $map['margin_status'] = 1;
                break;
            case 3: //集采成功
                $map['is_order'] = 1;
                break;
        }
        $list =$model->where($map)->where('create_time','BETWEEN',array(strtotime($begin_time),strtotime($end_time)))->order('create_time desc')->paginate(12, false, [
            'query' => $query,
        ]);
        if($promotiontType==4){
            foreach ($list as $k => $v) {
                $promotionInfo = $this->goodsModel->checkPromotionGoods($v['goods_id'],$promotiontType);
                $list[$k]['promotion_info'] = is_numeric($promotionInfo)?[]:$promotionInfo;
                /*格式化当前商品信息*/
                $skuInfo                     = $this->goodsSkuModel->find($v['sku_id'])->toArray();
                $goodsInfo=$this->goodsModel->getInfo($v['goods_id']);
                $goodsInfo                = array_merge($goodsInfo, $skuInfo);
                $goodsInfo                = format_goods_content($goodsInfo);
                $list[$k]['goodsInfo']=format_goods_content($goodsInfo);
                //获取当前集采单价
                $num=$model->where(['sku_id'=>$v['goods_id'],'margin_status'=>1])->sum('num');
                if(empty($num)){
                    $num=$v['num'];
                }
                $list[$k]['current_price']=$this->goodsModel->calcPrice($v['goods_price'],$num);
                $list[$k]['current_money']=$list[$k]['current_price']*$v['num'];
            }
        }
        //dump($list->toArray());
        $this->assign('list',$list);
        $this->assign('query', $query);
        $this->assign('orderGenre', $orderGenre);
        return $this->fetch($promotionTpl[$promotiontType].'_order');
    }
    /*
     * 优惠券订单
     * */
    public function couponOrder(){
        $member_uid   = $this->getMemberUid();
        if ($member_uid <= 0) {
            $this->error('用户信息错误，请重新登录!');
        }
        $map=[];
        $map['member_uid']=$member_uid;
        $list =$this->promotionCardOrderModel->where($map)->order('create_time desc')->paginate(12, false);
        foreach ($list as $k=>$v){
            /*15分钟过期卡券订单删除卡券，屏蔽掉过期订单*/
            if($v['end_time']<time()){
                $this->promotionCardItemModel->delData($v['item_id']);
                unset($list[$k]);
            }
            $list[$k]['cardInfo']=$this->promotionCardModel->get($v['card_id']);
            $list[$k]['itemInfo']=$this->promotionCardItemModel->get($v['item_id']);
        }
        $device= is_mobile();
        $this->assign('device',$device);
        $this->assign('list',$list);
        return $this->fetch();
    }

    /*
     * 订单详情
     */
    public function orderInfo()
    {
        $orderSn                = $this->request->param('order_sn', '');
        $orderInfo              = $this->orderModel->where('order_sn', $orderSn)->find();
        $orderInfo['item_list'] = $this->orderGoodsModel->where('order_id', $orderInfo['order_id'])->select();
        $orderInfo['log_list']  = $this->orderLogModel->where('order_id', $orderInfo['order_id'])->select();
        if ($this->request->isAjax()) {
            return $orderInfo;
        }
        $this->assign('orderInfo',$orderInfo);
        return $this->fetch();
    }

    /**
     * 余额支付
     */
    public function userpay(){
        if($this->request->isPost()){
            $payCode = $this->request->param('pay_code');
            $userModel = new UserModel();
            $userInfo = $userModel->getInfo('member',$this->getMemberUid());
            $orderSn = $this->request->param('order_sn');
            $orderInfo = $this->orderModel->where('order_sn',$orderSn)->find();
            if($payCode=='userpay'){

                //扣除用户余额
                $userMemberAccountModel = new UserMemberAccountModel();
                $accountData = [
                    'site_id'=>$orderInfo['site_id'],
                    'member_uid'=>$orderInfo['buyer_uid'],
                    'event'=>3,
                    'amount'=>$orderInfo['order_price'],
                    'order_sn'=>$orderInfo['order_sn']
                ];
                $account = $userMemberAccountModel->changeAccount($accountData);
                if($account===false){
                    $this->error($userMemberAccountModel->getError());
                }

            }
            $result = $this->orderModel->payOrder($userInfo['username'],$orderSn,$payCode,"[{$orderSn}]选用{$payCode}付款");
            if($result===false){
                $this->error($this->orderModel->getError());
            }else{
                $this->success('支付成功~！');
            }
        }else{
            $this->error('来路不明！');
        }

    }
    /**
     * 确认收货
     */
    public function orderFinnshed()
    {
        $orderId    = $this->request->param('order_id/d');
        $result     = $this->orderModel->finnshedOrder($this->userInfo['username'], $orderId);
        if ($result === false) {
            $this->error($this->orderModel->getError());
        }
        $this->success('操作成功！');
    }

    /**
     * 关闭订单
     */
    public function orderClose()
    {
        $orderId    = $this->request->param('order_id/d');
        $result     = $this->orderModel->closeOrder($this->userInfo['username'], $orderId);
        if ($result === false) {
            $this->error($this->orderModel->getError());
        }
        $this->success('操作成功！');
    }

    /**
     * 订单商品评价
     */
    public function orderGeval(){
        if($this->request->isPost()){
            $orderId    = $this->request->param('order_id/d');
            $shippingScores = $this->request->param('shipping_scores');
            $serverScores = $this->request->param('server_scores');
            $gevalScores = $this->request->param('geval_scores');
            $gevalContent = $this->request->param('geval_content');
            $gevalImage = $this->request->param('geval_image/a');
            $isAnonymous = $this->request->param('is_anonymous',0);
            if(empty($shippingScores)){
                $this->error('请对物流情况进行评分');
            }
            if(empty($serverScores)){
                $this->error('请对我们的服务进行评分');
            }
            if(empty($gevalScores)){
                $this->error('请对您购买的商品进行评分');
            }
            $goodsGevalModel = new ShopGoodsGevalModel();
            $result = $goodsGevalModel->addGeval($orderId,$shippingScores,$serverScores,$gevalScores,$gevalContent,$gevalImage,$isAnonymous);
            if ($result === false) {
                $this->error($goodsGevalModel->getError());
            }
            $this->success('评价完成，感谢您的参与！','index');
        }
        $orderSn                = $this->request->param('order_sn', '');
        $orderInfo              = $this->orderModel->where('order_sn', $orderSn)->find();
        $orderInfo['item_list'] = $this->orderGoodsModel->where('order_id', $orderInfo['order_id'])->select();
        $orderInfo['log_list']  = $this->orderLogModel->where('order_id', $orderInfo['order_id'])->select();
        $orderInfo['geval']  = $this->orderGevalModel->where('order_sn', $orderInfo['order_sn'])->find();
        $this->assign('orderInfo',$orderInfo);
        return $this->fetch();
    }
    /*申请退款*/
    function refund(){
        $order_sn=$this->request->param('order_sn');
        $price=$this->request->param('price');
        $refund_amount=$this->request->param('refund_amount');
        $buyer_message=$this->request->param('buyer_message');
        if($refund_amount>$price){
            $this->error('申请退款金额大于实际支付金额');
        }
        if(empty($buyer_message)){
            $this->error('请输入退款原因');
        }
        if($this->orderRefundModel->addRefund($order_sn,$refund_amount,$buyer_message)){
            $this->success('退款申请提交成功，请等待审核！');
        }else{
            $this->error($this->orderRefundModel->getError());
        }
    }
    /*上传支付凭证*/
    function voucher(){
        $data['order_id']=$this->request->param('order_id');
        $data['voucher']=$this->request->param('voucher');
        $this->orderModel->editData($data);
        $this->success('上传成功，请等待审核！');
    }

}
